package com.beck.code.generator;

import com.beck.code.generator.configProperty.JdbcConnectionConfig;
import lombok.Data;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author CuiJianbo
 * @since 2025/7/1
 */
@Data
public class JDBCConnectionFactory {

    private String username;
    private String password;
    private String connectionURL;
    private String driverClass;

    public JDBCConnectionFactory(JdbcConnectionConfig config) {
        this.username = config.getUsername();
        this.password = config.getPassword();
        this.connectionURL = config.getConnectionURL();
        this.driverClass = config.getDriverClass();
    }

    public Connection getConnection() throws SQLException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Properties props = new Properties();
        props.setProperty("user", this.username);
        props.setProperty("password", this.password);
        Driver driver = this.getDriver();
        return driver.connect(this.connectionURL, props);
    }

    private Driver getDriver() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> clazz = Class.forName(this.driverClass);
        return (Driver) clazz.getConstructor().newInstance();
    }


}
